﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Net;
using System.IO;
using System.Web.Script.Serialization;
using LiquidacionComision.CategoriaService;
using LiquidacionComision;
using LiquidacionComision.Excepciones;

namespace LiquidacionComision.Controllers
{
    [HandleError]
    public class CategoriaController : Controller
    {
 
        private string categoriaRESTService = "http://localhost:7446/CategoriasImpl.svc/Categorias";
        JavaScriptSerializer js = new JavaScriptSerializer();

        public ActionResult Iniciar()
        {            
            //Listar categorias
            string codigo = (Request.QueryString["busCodigo"] == null) ? string.Empty : Request.QueryString["busCodigo"];
            string nombre = (Request.QueryString["busNombre"] == null) ? string.Empty : Request.QueryString["busNombre"];
            string url = string.Empty;
            List<Categoria> lstCategorias = new List<Categoria>();            

            try
            {
                if (codigo ==string.Empty && nombre == string.Empty)
                {
                    url = categoriaRESTService + "/ListarTodos";
                }
                else if ( nombre == string.Empty)
                {
                    url = categoriaRESTService + "/ListarCategoriasPorCodigo/" + codigo;
                }
                else if ( codigo == string.Empty)
                {
                    url = categoriaRESTService + "/ListarCategoriasPorNombre/" + nombre;
                }
                else
                {
                    url = categoriaRESTService + "/ListarCategorias/" + codigo + "/" + nombre;
                }

                
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
                req.Method = "GET";
                HttpWebResponse res = (HttpWebResponse)req.GetResponse();
                StreamReader reader = new StreamReader(res.GetResponseStream());
                string objetoJson = reader.ReadToEnd();
                lstCategorias = js.Deserialize<List<Categoria>>(objetoJson);              
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message.ToString() + " : <br />" + url);
            }
            
            TempData["Categorias"] = lstCategorias;

            return View();
        }

        public ActionResult About()
        {
            return View();
        }

        public ActionResult EliminarCategoria(FormCollection formCollection)
        {
            string codigo = (formCollection["codigo"] == null) ? string.Empty : formCollection["codigo"];            
            string url = string.Empty;
            try
            {
                url = categoriaRESTService + "/EliminarCategoria/" + codigo;
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
                req.Method = "GET";
                HttpWebResponse res = (HttpWebResponse)req.GetResponse();
                StreamReader reader = new StreamReader(res.GetResponseStream());
                string objetoJson = reader.ReadToEnd();
                Response.Write(objetoJson);
            }
            catch (WebException e)
            {
                HttpWebResponse resError = (HttpWebResponse)e.Response;
                StreamReader reader2 = new StreamReader(resError.GetResponseStream());
                string error = reader2.ReadToEnd();
                JavaScriptSerializer js = new JavaScriptSerializer();
                Excepcion Ex = js.Deserialize<Excepcion>(error);
                Response.Write(Ex.ValidationError);
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message.ToString());
            }
            return null;
        }

        public ActionResult RegistrarCategoria()
        {
            string codigo = (Request.QueryString["codigo"] == null) ? string.Empty : Request.QueryString["codigo"];
            string nombre = (Request.QueryString["nombre"] == null) ? string.Empty : Request.QueryString["nombre"];
            string precio = (Request.QueryString["precio"] == null) ? string.Empty : Request.QueryString["precio"];
            string resultado = string.Empty;
            string url = string.Empty;

            try
            {
                float precioFloat = 0;
                bool convertido = float.TryParse(precio, out precioFloat);
                precioFloat = (convertido) ? precioFloat : 0;
                Categoria categoria = null;

                url = categoriaRESTService + "/RegistrarCategoria/" + codigo + "/" + nombre + "/" + precio;
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
                req.Method = "GET";
                HttpWebResponse res = (HttpWebResponse)req.GetResponse();
                StreamReader reader = new StreamReader(res.GetResponseStream());
                string objetoJson = reader.ReadToEnd();
                categoria = js.Deserialize<Categoria>(objetoJson);
                if (categoria != null)
                {
                    resultado = Constantes.PROCESO_CORRECTO;
                }
                else 
                {
                    resultado = Constantes.PROCESO_ERROR;
                }
                Response.Write(resultado);
            }
            catch (WebException e)
            {
                HttpWebResponse resError = (HttpWebResponse)e.Response;
                StreamReader reader2 = new StreamReader(resError.GetResponseStream());
                string error = reader2.ReadToEnd();
                JavaScriptSerializer js = new JavaScriptSerializer();        
                Excepcion Ex = js.Deserialize<Excepcion>(error);
                Response.Write(Ex.ValidationError); 
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message.ToString());
            }
            return null;
        }

        public ActionResult ObtenerCategoria(FormCollection formCollection)
        {            
            Categoria categoria = null;
            string codigo = (Request.QueryString["codigo"] == null) ? string.Empty : Request.QueryString["codigo"];
            string url = string.Empty;
            try
            {
                url = categoriaRESTService + "/ObtenerCategoria/" + codigo;
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
                req.Method = "GET";
                HttpWebResponse res = (HttpWebResponse)req.GetResponse();
                StreamReader reader = new StreamReader(res.GetResponseStream());
                string objetoJson = reader.ReadToEnd();
                categoria = js.Deserialize<Categoria>(objetoJson);
                Response.Write(categoria.Codigo + ",,," + categoria.Nombre + ",,," + categoria.Precio);
            }
            catch (Exception ex) {
                Response.Write(ex.Message.ToString() + " : <br />" + url);
            }
            return null;
        }

        public ActionResult ModificarCategoria()
        {
            string codigo = (Request.QueryString["codigo"] == null) ? string.Empty : Request.QueryString["codigo"];
            string nombre = (Request.QueryString["nombre"] == null) ? string.Empty : Request.QueryString["nombre"];
            string precio = (Request.QueryString["precio"] == null) ? string.Empty : Request.QueryString["precio"];            
            string resultado = string.Empty;
            string url = string.Empty;

            try
            {
                float precioFloat = 0;
                bool convertido = float.TryParse(precio, out precioFloat);
                precioFloat = (convertido) ? precioFloat : 0;

                Categoria categoria = new Categoria();
                categoria.Codigo = codigo;
                categoria.Nombre = nombre;
                categoria.Precio = precioFloat;

                url = categoriaRESTService + "/ModificarCategoria/" + codigo + "/" + nombre + "/" + precio;
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
                req.Method = "GET";
                HttpWebResponse res = (HttpWebResponse)req.GetResponse();
                StreamReader reader = new StreamReader(res.GetResponseStream());
                string objetoJson = reader.ReadToEnd();
                categoria = js.Deserialize<Categoria>(objetoJson);
                if (categoria != null)
                {
                    resultado = Constantes.PROCESO_CORRECTO;
                }
                else
                {
                    resultado = Constantes.PROCESO_ERROR;
                }
                Response.Write(resultado);
            }
            catch (WebException e)
            {
                HttpWebResponse resError = (HttpWebResponse)e.Response;
                StreamReader reader2 = new StreamReader(resError.GetResponseStream());
                string error = reader2.ReadToEnd();
                JavaScriptSerializer js = new JavaScriptSerializer();
                Excepcion Ex = js.Deserialize<Excepcion>(error);
                Response.Write(Ex.ValidationError);
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message.ToString() + ":" + url);
            }
            
            return null;
        }
    
    }
}
